import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutterapp2/base/base_test_widget.dart';
import 'package:flutterapp2/extension/extension.dart';
import 'package:fluttertoast/fluttertoast.dart';

class TestFormPage extends BaseTestWidget {
  String title = "新增表单";
  bool expand = true;
  bool isValid = true;
  String price = "100.2";

  //输入框焦点管理对象
  List<FocusNode> focusNodes = List.generate(3, (index) => FocusNode());

  //管理输入框焦点对象的对象
  FocusScopeNode focusScope;

  @override
  void initState() {
    super.initState();
    //焦点对象管理对象初始化
    Future.delayed(Duration.zero, () => focusScope = FocusScope.of(context));
    focusNodes[0].addListener(() {
      if (!focusNodes[0].hasFocus) {
        print('失去焦点');
      } else {
        print('得到焦点');
      }
    });
  }

  @override
  Widget getBody(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: 200,
            ),
            Row(
              children: <Widget>[
                Text(title ?? "").expanded(),
                Icon(expand ? Icons.arrow_drop_down : Icons.arrow_drop_up).click(() {
                  setState(() {
                    expand = !expand;
                  });
                }),
              ],
            ),
            SizedBox(
              height: 10,
            ),
            Row(
              children: <Widget>[
                TextField(
                  autofocus: true,
                  focusNode: focusNodes[0],
//                  maxLines: null, // 不限制行数，达到宽度后自动换行
                  cursorColor: Colors.blue,
                  onSubmitted: (text) {
                    // 自动切换焦点到下一个文本框
                    changedFocusNode();
                  },
                  maxLength: 50,
//              textAlign: TextAlign.center,
//                keyboardType: TextInputType.multiline,
                  decoration: InputDecoration(
                    hintText: '请输入用户名',
                    //hintStyle: TextStyle(fontSize: 14),
                    contentPadding: const EdgeInsets.all(5),
                  ),
                ).expanded(),
                SizedBox(
                  width: 10,
                ),
                Icon(Icons.cloud_upload).click(() {
                  // todo check
                  setState(() {
                    isValid = title.length >= 5;
                  });
                }),
              ],
            ).visible(expand),
            Text(
              "长度不能少于5",
              style: TextStyle(color: Colors.red),
            ).visible(!isValid),
            SizedBox(
              height: 10,
            ),
            TextField(
//                controller:,
              onChanged: (text) {
                title = text;
              },
              onSubmitted: (text) {
                // 自动切换焦点到下一个文本框
                changedFocusNode();
              },
              cursorColor: Colors.blue,
//              textAlign: TextAlign.center,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                hintText: '请输入密码',
                //hintStyle: TextStyle(fontSize: 14),
                contentPadding: const EdgeInsets.all(5),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(2.0),
                  borderSide: BorderSide(
                    width: 0.5,
                    color: Colors.blue,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(2.0),
                  borderSide: BorderSide(
                    width: 0.5,
                    color: Colors.blue,
                  ),
                ),
              ),
              focusNode: focusNodes[1],
            ) /*.expanded()*/,
            TextField(
              cursorColor: Colors.blue,
              controller: TextEditingController.fromValue(TextEditingValue(
                text: price,
                selection: TextSelection.fromPosition(
                    TextPosition(affinity: TextAffinity.downstream, offset: price?.length ?? 0)),
              )),
              onChanged: (text) {
                price = text;
              },
              onSubmitted: (text) {
                // 自动切换焦点到下一个文本框
                changedFocusNode();
//                Fluttertoast.showToast(msg: "点击了回车键");
              },
//              keyboardType: TextInputType.multiline,
              inputFormatters: [
//                WhitelistingTextInputFormatter(RegExp("[a-zA-Z]")),// 只允许输入字母
//                WhitelistingTextInputFormatter.digitsOnly,// 只允许输入数字
                _MyNumberTextInputFormatter(digit: 2), //限制小数位数
              ],
              textInputAction: TextInputAction.done,
              decoration: InputDecoration(
                hintText: '请输入单价',
                //hintStyle: TextStyle(fontSize: 14),
                contentPadding: const EdgeInsets.all(5),
              ),
              focusNode: focusNodes[2],
            ),
            //绘制按钮布局
            Column(
              children: <Widget>[
                RaisedButton(
                  onPressed: () {
                    changedFocusNode();
                  },
                  child: Text("移动焦点"),
                ),
                RaisedButton(
                  onPressed: () {
                    //让聚焦的输入框失去焦点或者new一个新的聚焦
//                  userFocusNode.unfocus();
//                  pwdFocusNode.unfocus();
                    focusScope.requestFocus(FocusNode());
                  },
                  child: Text("关闭软键盘"),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  changedFocusNode() {
    //进行输入框焦点的转移
    var focusIndex = focusNodes.indexWhere((node) => node.hasFocus, -1);
    focusScope.requestFocus(focusNodes[(focusIndex + 1) % 3]);
  }

  @override
  void dispose() {
    super.dispose();
    focusScope.requestFocus(FocusNode());
  }

  @override
  String getTitle() {
    return "TestFormPage";
  }
}

// 限制小数位数
class _MyNumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;

  ///允许的小数位数，-1代表不限制位数
  int digit;

  _MyNumberTextInputFormatter({this.digit = -1});

  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  ///获取目前的小数位数
  static int getValueDigit(String value) {
    if (value.contains(".")) {
      return value.split(".")[1].length;
    } else {
      return -1;
    }
  }

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value != "" &&
            value != defaultDouble.toString() &&
            strToFloat(value, defaultDouble) == defaultDouble ||
        getValueDigit(value) > digit) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
